namespace Digitalmes.Application.Mes;

/// <summary>
/// 生产工单服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class ProdWoService : IDynamicWebApiService
{
    private readonly SugarRepository<ProdWo> _thisRepository;

    public ProdWoService(SugarRepository<ProdWo> thisRepository)
    {
        _thisRepository = thisRepository;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProdWoDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .Includes(s => s.Product)
            .WhereIF(!string.IsNullOrWhiteSpace(param.Key), s => s.Wo.Contains(param.Key))
            .OrderByDescending(s => s.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ProdWoDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ProdWoDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(s => s.Product)
            .FirstAsync(s => s.Id == id);
        return model.Adapt<ProdWoDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ProdWoDto model)
    {
        if (await _thisRepository.IsAnyAsync(s => s.Wo == model.Wo))
        {
            Oops.ThrowBah(ErrCode.E4002);
        }

        var wo = model.Adapt<ProdWo>();
        wo.SetStatus(WoStatusEnum.Created);
        return await _thisRepository.InsertAsync(wo);
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ProdWoDto model)
    {
        // 生产中的工单，不能编辑数据
        var wo = await _thisRepository.GetByIdAsync(model.Id);

        // 编号不能重复
        if (wo.Wo != model.Wo)
        {
            Oops.ThrowBah(ErrCode.E4002);
        }

        // 只有处于"创建"状态的工单才能修改
        if (wo.Status != WoStatusEnum.Created)
        {
            Oops.ThrowBah(ErrCode.E4011);
        }

        return await _thisRepository.UpdateAsync(model.Adapt<ProdWo>(), s => new
        {
            s.ProductId,
            s.ProductCode,
            s.TotalQty,
            s.Source,
            s.PlanStartTime,
            s.PlanEndTime,
            s.BatchNo,
            s.UpdateTime,
            s.UpdateUser
        });
    }

    /// <summary>
    /// 工单下发
    /// </summary>
    /// <param name="models"></param>
    /// <returns></returns>
    [HttpPut]
    public async Task<bool> IssueAsync(List<ProdWoDto> models)
    {
        var ids = models.Select(s => s.Id).ToArray();
        var items = await _thisRepository.GetListAsync(s => ids.Contains(s.Id) && s.Status == WoStatusEnum.Created);
        if (items.Any())
        {
            items.ForEach(s =>
            {
                s.SetStatus(WoStatusEnum.Issued);
            });

            await _thisRepository.UpdateAsync(items, s => new { s.Status, s.LastStatus, s.UpdateTime, s.UpdateUser });
        }

        return true;
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody] List<long> ids)
    {
        // 仅有"创建"状态的工单才能删除
        var items = await _thisRepository.GetListAsync(s => ids.Contains(s.Id) && s.Status == WoStatusEnum.Created);
        if (items.Any())
        {
            return await _thisRepository.DeleteAsync(items);
        }

        return true;
    }
}
